package cn.stylefeng.guns.modular.gridsystem.netty.ws;

import cn.stylefeng.guns.modular.gridsystem.config.WsServerConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;

/**
 * @author ssy
 * @date 2022/1/10 14:34
 */
@Slf4j
public class WsServer {

    @Autowired
    private WebSocketChannelHanlder webSocketChannelHanlder;

    @Autowired
    private WsServerConfig serverConfig;

    @Async
    public void run() {
        log.info("ws server 启动中。。。");
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap sb = new ServerBootstrap();
            sb.group(bossGroup, workerGroup);
            sb.channel(NioServerSocketChannel.class);
            sb.childOption(ChannelOption.SO_KEEPALIVE, true); //保持长连接
            sb.childHandler(new ChannelInitializer() {
                @Override
                protected void initChannel(Channel channel) throws Exception {
                    ChannelPipeline pipeline = channel.pipeline();
                    pipeline.addLast(new HttpServerCodec());
                    pipeline.addLast(new ChunkedWriteHandler());
                    pipeline.addLast(new HttpObjectAggregator(1024 * 10));
                    pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
                    pipeline.addLast(webSocketChannelHanlder);
                }
            });

            ChannelFuture future = sb.bind(serverConfig.getPort()).sync();
            log.info("ws server 启动成功。。。");
            future.channel().closeFuture().await();
        } catch (InterruptedException e) {
            e.printStackTrace();
            log.info("运行出错：" + e);
        } finally {
            bossGroup.shutdownGracefully(); //关闭线程组
            workerGroup.shutdownGracefully();
        }
    }

}
